/**
 * 
 */
package soa.security.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;

import soa.security.dao.AccountDao;
import soa.security.dao.OrganizationDao;
import soa.security.domain.Account;
import soa.security.domain.Organization;
import soa.security.domain.Person;
import soa.security.mgr.service.AccountMgrService;
import soa.security.mgr.service.PersonMgrService;

/**
 * @author Cre.Gu
 *
 */
public class SoaCasFilter extends CasFilter {

	@Resource
	protected AccountDao accountDao;
	@Resource
	protected OrganizationDao organizationDao;
	@Resource
	protected PersonMgrService personMgrService;
	@Resource
	protected AccountMgrService accountMgrService;

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		String accountDn = (String) subject.getPrincipal();
		Account account = accountDao.findByDn(accountDn);

		try {
			String organizationDn = WebUtils.getCleanParam(request,
					"organizationDn");
			
			if (StringUtils.isBlank(organizationDn)) {
				organizationDn = accountDn.substring(accountDn.indexOf("bid=OR"));
			}
			
			if (StringUtils.isNotBlank(organizationDn)
					&& !"-1".equals(organizationDn)) {
				Organization or = organizationDao.findByDn(organizationDn);
				subject.getSession().setAttribute(
						LdapAuthenticationFilter.SESSION_ORGANIZATION_KEY, or);

				Person person = personMgrService.findByUid(
						account.getPersonBid(), or.getBid());
				account.setPerson(person);
			}
		} catch (Exception e) {
		}

		subject.getSession().setAttribute(
				LdapAuthenticationFilter.SESSION_ACCOUNT_KEY, account);

		return super.onLoginSuccess(token, subject, request, response);
	}

}
